package response

import (
	"errors"
	"gin-admin/global"
	"net/http"

	"github.com/gin-gonic/gin"
)

func Result(ctx *gin.Context, code int64, message string, data interface{}) {
	if message == "" {
		status := GetStatusCode(code)
		message = status.Message
	}

	ctx.JSON(http.StatusOK, Response{
		Code:    code,
		Message: message,
		Data:    data,
	})
}

func Success(ctx *gin.Context, data interface{}) {
	Result(ctx, SuccessCode, GetStatusCode(SuccessCode).Message, data)
}

func SuccessNoData(ctx *gin.Context) {
	Success(ctx, nil)
}

func SuccessWithList(ctx *gin.Context, page, size int, total int64, list []interface{}) {
	responseData := PaginationResponse{
		Page:  page,
		Size:  size,
		Total: total,
		List:  list,
	}
	Success(ctx, responseData)
}

func SuccessWithPage[T any](ctx *gin.Context, data PageResponse[T]) {
	Success(ctx, data)
}

func Failed(ctx *gin.Context) {
	Result(ctx, FailedCode, GetStatusCode(FailedCode).Message, nil)
}

func FailedWithCode(ctx *gin.Context, code int64) {
	Result(ctx, code, GetStatusCode(code).Message, nil)
}

func NewServiceError(code int64, err error) *ServiceError {
	return &ServiceError{
		Code: code,
		Err:  err,
	}
}

func (e *ServiceError) Error() string {
	if e.Err != nil {
		return e.Err.Error()
	}
	return "未知错误"
}

func WrapError(code int64, message string) *ServiceError {
	err := errors.New(message)
	global.GA_LOGGER.Sugar().Errorw("操作发生错误", "error", err)
	return NewServiceError(code, err)
}
